<?php

namespace Laoha\Nav;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;


class LaohaNav extends Model
{
    protected $table = 'laoha_navs';
	//protected $fillable = ['name', 'title', 'parent_id', 'table_id'];


	
	use AdminBuilder, ModelTree {
        ModelTree::boot as treeBoot;
    }

    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct($root=0)
    {        
		if($root){
			static::addGlobalScope('avaiable',function(Builder $builder) use($root){
					$builder->where('root',$root);
			});
		}
        parent::__construct();
    }


    /**
     * determine if enable menu bind permission.
     *
     * @return bool
     */
    public function scopeRoot($query, $root)
    {
        return $query->where('root', $root);
    }


    public function getnode($parentId = 0,$nodes=[])
    {
        $branch = [];
        if (empty($nodes)) {
            $nodes = $this->allNodes();
        }
        foreach ($nodes as $node) {
            if ( $node['parent_id'] == $parentId ) {
                $children = $this->buildNestedArray($nodes, $node['id']);

                if ($children) {
                    $node['children'] = $children;
                }

                $branch[] = $node;
            }
        }
        return $branch;
    }

    public function getnodeids($parentId=0)
    {
		$nodes = $this->allNodes();
		$ids[] = $parentId;
        foreach ($nodes as $k=>$node) {	
			if( in_array($node['parent_id'],$ids) ){
					$ids[]=$node['id'];
			}
        }
        return $ids;
    }

    /**
     * {@inheritdoc}
     */
    public function delete()
    {
        $ids = $this->getnodeids($this->getKey());
		if($ids && count($ids)>1){
			unset($ids[0]);
			if($ids) $this->whereIn('id',$ids)->delete();
		}
        return parent::delete();
    }


}
